package com.blog.data;

import java.util.Map;

public class SqlFactory {

	public String generateUpdateSql( String table, Map<String, Object> fields, String key ){
		StringBuffer sql = new StringBuffer();
		StringBuffer fs = new StringBuffer();
		StringBuffer vals = new StringBuffer();
		
		sql.append(f("update %s set ",table));
		for( String k : fields.keySet() ){
			fs.append(f("`%s`=?,",k));
		}
		if( fs.length() > 1 ){
			fs = fs.delete(fs.length() - 1, fs.length());
		}
		if( key != null && !key.isEmpty() ){
			vals.append(" where");
			for( String k : key.split(",") ){
				vals.append(f(" `%s`=? and",k));
			}
			vals.delete(vals.length() - 3, vals.length());
		}
		return sql.toString() + fs.toString() + vals.toString();
	}
	
	public String generateInsertSql( String table, Map<String, Object> fields ){
		
		StringBuffer sql = new StringBuffer();
		StringBuffer fs = new StringBuffer();
		StringBuffer vals = new StringBuffer();
		
		sql.append(f("insert into `%s` ",table));
		fs.append(" (");
		vals.append(" values(");
		
		for( String k : fields.keySet() ){
			fs.append(f(" `%s` ,",k));
			vals.append(f(" ?,"));
		}
		
		fs.deleteCharAt(fs.length()-1);
		vals.deleteCharAt(vals.length()-1);
		
		fs.append(")");
		vals.append(")");
		
		sql.append(fs).append(vals);
		return sql.toString();
	}
	
	public String generateDelSql( String table, String primaryKey){
		StringBuffer sql = new StringBuffer();
		sql.append(f("delete from `%s` where ",table));
		
		boolean isFirst = true;
		for( String k : primaryKey.split(",") ){
			if( !isFirst ){
				sql.append(" and ");
			}
			sql.append(f(" `%s` = ?",k));
			isFirst = false;
		}
		
		return sql.toString();
	}
	
	public String generateGetSqlByKey( String table,String key ){
		StringBuffer sql = new StringBuffer();
		sql.append(f("select * from `%s`",table));
		if( key != null && !key.isEmpty() ){
			sql.append(" where ");
			for( String k : key.split(",") ){
				sql.append(f(" `%s`=? and",k));
			}
			sql = sql.delete(sql.length() - 3, sql.length());
		}
		return sql.toString();
	}
	
	public String generateGetSqlByWhere( String table, String where ){
		StringBuffer sql = new StringBuffer();
		sql.append( f("select * from `%s` ",table) );
		if( (where != null) && !where.isEmpty() ){
			sql.append(where);
		}
		return sql.toString();
	}
	
	public String f( String str, Object ... params ){
		return String.format(str, params);
	}
	
}
